package com.app.xinfadi.widget.image_browser;

import android.annotation.SuppressLint;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.GestureDetector;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.app.xinfadi.R;
import com.app.xinfadi.base.BaseActivity;
import com.app.xinfadi.base.Constant;
import com.app.xinfadi.util.BitmapUtils;
import com.app.xinfadi.util.FileUtil;
import com.app.xinfadi.util.LogUtil;
import com.app.xinfadi.util.Toast;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;
import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener;
import com.polites.android.GestureImageView;

import java.util.List;
import java.util.UUID;


/**
 * 图片浏览 左右滑动
 * 
 * @Function: TODO <br/>
 * @date 2015-3-17 下午2:31:50 <br/>
 * @author WuTengFei <br/>
 * 
 */
public class ImageExploreActivity extends BaseActivity {
	private ViewPager myViewPager1;
	protected int beforePosition = 0;
	private int currentPosition = 0;
	private MinePagerAdapter adapter;
	protected String TAG = "ImageExploreActivity1";
	private List<String> imageUrl;
	// private List<GestureImageView> gestureImageViews;
	private View title_bar;
	private TextView currrent_page;
	private TextView all_page;
	private ImageView back_tv;
	private TextView save_tv;
	private DisplayImageOptions options;

	@Override
	protected void onCreate(Bundle bundle) {
		super.onCreate(bundle);
		setContentView(R.layout.image_explore);
		options = new DisplayImageOptions.Builder().resetViewBeforeLoading(true).cacheOnDisk(true)
				.imageScaleType(ImageScaleType.EXACTLY).bitmapConfig(Bitmap.Config.RGB_565)
				.displayer(new FadeInBitmapDisplayer(300)).build();
//		getSupportActionBar().hide();
		getBundle();
		myViewPager1 = (ViewPager) findViewById(R.id.myViewPager1);
		currrent_page = (TextView) findViewById(R.id.currrent_page);
		all_page = (TextView) findViewById(R.id.all_page);
		title_bar = findViewById(R.id.title_bar);
		back_tv = (ImageView) findViewById(R.id.back_tv);
		back_tv.setOnClickListener(this);
		save_tv = (TextView) findViewById(R.id.save_tv);
		save_tv.setOnClickListener(this);
		initHomePic();
		myViewPager1.setOnPageChangeListener(new OnPageChangeListener() {

			@SuppressLint("NewApi")
			@Override
			public void onPageSelected(int position) {
				// 切换点的状态
				currentPosition = position;
				// LogUtil.e(TAG, "onPageSelected：" + "position" + position +
				// " before:" + beforePosition);
				// 把前一个的点置为false
				if (beforePosition != -1) {
					// LogUtil.d(TAG, "before:" +
					// gestureImageViews.get(beforePosition).getId());
					// gestureImageViews.get(beforePosition).recoverSize();
				}
				currrent_page.setText(position + 1 + "");
				beforePosition = position;
			}

			@Override
			public void onPageScrollStateChanged(int position) {

			}

			@Override
			public void onPageScrolled(int arg0, float arg1, int arg2) {

			}
		});

	}

	private void getBundle() {
		imageUrl = getIntent().getStringArrayListExtra("imageUrlList");
		currentPosition = getIntent().getIntExtra("currentPosition", 0);
	}

	@SuppressLint("NewApi")
	public void initHomePic() {
		all_page.setText(imageUrl.size() + "");
		currrent_page.setText("1");
		// gestureImageViews = new ArrayList<GestureImageView>();
		// for (int i = 0; i < imageUrl.size(); i++) {
		// GestureImageView imageView = new GestureImageView(context);
		// imageView.setMinScale((float) 0.75);
		// imageView.setMaxScale(10);
		// imageView.setScaleType(ScaleType.CENTER_INSIDE);
		// gestureImageViews.add(imageView);
		// }
		myViewPager1.setVisibility(View.VISIBLE);
		adapter = new MinePagerAdapter();
		myViewPager1.setAdapter(adapter);
		myViewPager1.setPageMargin(60);
		adapter.notifyDataSetChanged();
		myViewPager1.setCurrentItem(currentPosition, false);
		currrent_page.setText(currentPosition + 1 + "");
	}

	@Override
	public void onClick(View v) {
		super.onClick(v);
		switch (v.getId()) {
		case R.id.back_tv:
			finish();
			break;
		case R.id.save_tv:
			LogUtil.e(TAG, "保存图片:" + imageUrl.get(currentPosition));
			ImageView imageView = new ImageView(context);
			ImageLoader.getInstance().displayImage(imageUrl.get(currentPosition), imageView,
					new SimpleImageLoadingListener() {
						@Override
						public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
							super.onLoadingComplete(imageUri, view, loadedImage);
							LogUtil.e(TAG,"onLoadingComplete");
							UUID uuid = UUID.randomUUID();
							FileUtil.MakeFile(Constant.IMAGE_SAVE_PATH);
							if (BitmapUtils.saveToSdCard(Constant.IMAGE_SAVE_PATH + uuid + ".png", loadedImage)) {
								Toast.makeText(context, "保存至手机相册!", Toast.LENGTH_SHORT).show();
							}
						}

						@Override
						public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
							super.onLoadingFailed(imageUri, view, failReason);
							Toast.makeText(context, "保存失败!", Toast.LENGTH_SHORT).show();
						}
					});

			break;
		default:
			break;
		}
	}

	public class MinePagerAdapter extends PagerAdapter {

		public MinePagerAdapter() {

		}

		@Override
		public int getItemPosition(Object object) {
			return super.getItemPosition(object);
		}

		@Override
		public int getCount() {
			return imageUrl.size();
		}

		@Override
		public boolean isViewFromObject(View arg0, Object arg1) {
			return arg0 == arg1;
		}

		@Override
		public void destroyItem(ViewGroup container, int position, Object object) {
			((ViewPager) container).removeView((View) object);
			// LogUtil.d("ViewPager", "-<<销毁" + position + "页");
		}

		@Override
		public Object instantiateItem(ViewGroup container, final int position) {
			// GestureImageView imageView = gestureImageViews.get(position);
			View imageLayout = LayoutInflater.from(context).inflate(R.layout.image_explore_pager_item, null);
			GestureImageView imageView = (GestureImageView) imageLayout.findViewById(R.id.gestureImageView);
			final ProgressBar spinner = (ProgressBar) imageLayout.findViewById(R.id.progressBar1);
			// imageView.setMinScale((float) 0.75);
			// imageView.setMaxScale(10);
			// imageView.setScaleType(ScaleType.CENTER_INSIDE);
			// ImageLoader.getInstance().displayImage(imageUrl.get(position),
			// imageView, options);

			ImageLoader.getInstance().displayImage(imageUrl.get(position), imageView, options,
					new SimpleImageLoadingListener() {
						@Override
						public void onLoadingStarted(String imageUri, View view) {
							spinner.setVisibility(View.VISIBLE);
						}

						@Override
						public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
							String message = null;
							switch (failReason.getType()) {
							case IO_ERROR:
								message = "Input/Output error";
								break;
							case DECODING_ERROR:
								message = "Image can't be decoded";
								break;
							case NETWORK_DENIED:
								message = "Downloads are denied";
								break;
							case OUT_OF_MEMORY:
								message = "Out Of Memory error";
								break;
							case UNKNOWN:
								message = "Unknown error";
								break;
							}
							// Toast.makeText(context, message,
							// Toast.LENGTH_SHORT).show();
							spinner.setVisibility(View.GONE);
						}

						@Override
						public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
							spinner.setVisibility(View.GONE);
						}
					});

			imageView.setOnTouchListener(new OnTouchListener() {

				@Override
				public boolean onTouch(View v, MotionEvent event) {
					tapDetector.onTouchEvent(event);
					return true;
				}
			});
			// LayoutParams layoutParams = new LayoutParams();
			// layoutParams.width = LayoutParams.MATCH_PARENT;
			// layoutParams.height = LayoutParams.MATCH_PARENT;
			container.addView(imageLayout);
			return imageLayout;
		}
	}

	final GestureDetector tapDetector = new GestureDetector(context, new SimpleOnGestureListener() {
		/**
		 * 这个方法不同于onSingleTapUp，他是在GestureDetector确信用户在第一次触摸屏幕后，
		 * 没有紧跟着第二次触摸屏幕，也就是不是“双击”的时候触发
		 */
		@Override
		public boolean onSingleTapConfirmed(MotionEvent e) {
			if (title_bar.getVisibility() == View.VISIBLE) {
				title_bar.setVisibility(View.GONE);
			} else {
				title_bar.setVisibility(View.VISIBLE);
			}
			return false;
		}
	});
}
